import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'HomePage',
    component: () => import('../views/HomePage.vue')
  },
  {
    path: '/login',
    name: 'UserLogin',
    component: () => import('../views/UserLogin.vue')
  },
  {
    path: '/register',
    name: 'UserRegister',
    component: () => import('../views/UserRegister.vue')
  },
  {
    path: '/emergency',
    name: 'EmergencyInfo',
    component: () => import('../views/EmergencyInfo.vue')
  },
  {
    path: '/hotels',
    name: 'HotelList',
    component: () => import('../views/tourist/HotelList.vue')
  },
  // 管理员路由
  {
    path: '/admin',
    component: () => import('../views/admin/AdminLayout.vue'),
    children: [
      {
        path: 'emergency',
        name: 'EmergencyManage',
        component: () => import('../views/admin/EmergencyManage.vue')
      },
      {
        path: 'hotel',
        name: 'HotelManage',
        component: () => import('../views/admin/HotelManage.vue')
      },
      {
        path: 'entertainment',
        name: 'EntertainmentManage',
        component: () => import('../views/admin/EntertainmentManage.vue')
      }
    ],
    beforeEnter: (to, from, next) => {
      const userStr = localStorage.getItem('user')
      if (!userStr) {
        next('/login')
        return
      }
      
      const user = JSON.parse(userStr)
      if (user.role === 'admin') {
        next()
      } else {
        next('/')
      }
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // 登录和注册页面不需要验证
  if (to.path === '/login' || to.path === '/register') {
    next()
    return
  }

  // 检查是否登录
  const userStr = localStorage.getItem('user')
  if (!userStr && to.path !== '/') {
    next('/login')
    return
  }

  next()
})

export default router 